package org.http.request;

import org.http.Const;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;

/**
 * @author andy
 */
public class HttpRequest implements Request{


    private String method;
    private String requestUri;
    private String protocol = "HTTP/1.1";
    private String host = "localhost";
    private int port = 80;
    private String contentType = "";

    private Map<String, String> parameters = new HashMap<>();
    private Map<String, String> headers = new HashMap<>();
    private String encoding = Const.encoding;
    private int bufferSize = 8192;
    private String requestBody = null;

    @Override
    public String getMethod() {
        return this.method;
    }

    @Override
    public String getRequestUri() {
        return this.requestUri;
    }

    @Override
    public String getProtocol() {
        return this.protocol;
    }

    @Override
    public String getHost() {
        return this.host;
    }

    @Override
    public int getPort() {
        return this.port;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public Map<String, String> getParameters() {
        return this.parameters;
    }

    @Override
    public String getParameter(String parameterName) {
        return this.parameters.get(parameterName);
    }

    @Override
    public Map<String, String> getHeaders() {
        return this.headers;
    }

    @Override
    public String getHeader(String headerName) {
        return this.headers.get(headerName);
    }

    @Override
    public void setCharEncoding(String encoding) {
        this.encoding = encoding;

        // 所在平台的行分隔符
        String lineSeparator = System.getProperty("line.separator");

        String body = null;
        try {
            body = URLDecoder.decode(requestBody, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String requestLine = body.substring(0, body.indexOf(lineSeparator));
        String[] requestLines = requestLine.split("\\s+");
        this.method = requestLines[0];
        this.protocol = requestLines[2];

        // 解析请求uri
        String[] uri = requestLines[1].split("\\?");
        this.requestUri = uri[0];
    }

    /**
     * 从socketChannel中解析到requestBody中
     * @param socketChannel 管道
     * @return 返回字符串
     * @throws IOException
     */
    public String resolveRequestBody(SocketChannel socketChannel) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
        int len = socketChannel.read(byteBuffer);

        if (len > 0) {
            byteBuffer.flip();
            requestBody = new String(byteBuffer.array(), 0, len);
            byteBuffer.clear();
        }
        return requestBody;
    }

}
